#include "client.h"
#define CONVERSION_NUM 1024 //内存单位进制转化
#define BAR_WIDTH 50 // 默认进度条宽度

void print_progress_bar(double percent) {
    int pos = (int)(percent * BAR_WIDTH) / 100;
    printf("\r[");
    for (int i = 0; i < BAR_WIDTH; i++) {
        if (i < pos) {
            printf("=");
        } else if (i == pos) {
            printf(">");
        } else {
            printf(" ");
        }
    }
    printf("] %5.2lf%%", percent);
    fflush(stdout); //刷新缓冲区
}

void putsCommand(int sockfd, train_t * pt)
{
    char filename[20] = {0};
    strcpy(filename, pt->buff);


    //发送文件名
    send(sockfd, filename, strlen(filename), 0);

    //获取文件的sha256码发送
    char result[128] = {0};
    hash_sha256(filename, result);
    send(sockfd, result, strlen(result),0);

    //接收查询结果
    int exist = -1;
    recv(sockfd, &exist, sizeof(exist), 0);

    if(exist == 0){
        //打开文件
        int fd = open(filename, O_RDWR);
        if(fd < 0) {
            perror("open"); return;
        }
        //获取文件大小
        struct stat st;
        memset(&st, 0, sizeof(st));
        fstat(fd, &st);

        //发送文件大小
        sendn(sockfd, &st.st_size, sizeof(st.st_size));

        // @zg 判断文件是否大于100MB, 若大于100MB则进行sendfile零拷贝传输
        int ret = 0;
        long size_in_mb = st.st_size / (CONVERSION_NUM * CONVERSION_NUM);
        if (size_in_mb > 100) {
            printf("large file is up...\n"); // 仅供调试
            off_t cur_size = 0; //当前已传输文件大小
            double percent = 0; // 传输百分比
            while(cur_size < st.st_size) {
                ret = sendfile(sockfd, fd, 0L, st.st_size);
                cur_size += ret;
                double new_percent = (double)100 * cur_size / st.st_size;
                if (new_percent != percent) {
                    print_progress_bar(new_percent);
                }
            }
            if (ret == -1) {
                perror("sendfile");
            }
            printf("\n"); //换行以结束进度条
            printf("large file send over.\n");
            close(fd);
            return;
        }
        printf("file length: %ld\n", st.st_size);
        off_t cur = 0;
        char buff[1000] = {0};
        //发送内容
        while(cur < st.st_size) {
            memset(buff, 0, sizeof(buff));
            ret = read(fd, buff, sizeof(buff));
            if(ret == 0) {
                break;
            }
            ret = sendn(sockfd, buff, ret);
            cur +=  ret;
        }
        //发送完成
        printf("file send over.\n");
        close(fd);
    }
}

